package ee.domain;

import com.opensymphony.xwork2.ActionSupport;
import ee.db.UserService;
import ee.model.User;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;

import javax.annotation.Resource;
import java.io.InputStream;
import java.io.StringBufferInputStream;

import static org.apache.commons.lang3.StringUtils.isEmpty;

public class Todos extends ActionSupport {
  @Resource
  private UserService userService;
  private InputStream inputStream;
  public String registeredLastName, registeredUserName, registeredEmail, registeredPassword, registeredFirstName;
  public String username, password;

  public InputStream getInputStream() {
    return inputStream;
  }

  @Override
  public String execute() throws Exception {
    return super.execute();
  }

  @Action(value = "show", results = {
  })
  public String show() {
    return SUCCESS;
  }

  @Action(value = "registerUser", results = {
  })
  public String registerUser() {
    if (isEmpty(registeredPassword) || isEmpty(registeredUserName) || isEmpty(registeredEmail)) {
      return SUCCESS;
    }
    User user = new User(registeredFirstName, registeredLastName, registeredUserName, registeredEmail);
    user.setPassword(registeredPassword);
    userService.saveUser(user);
    addActionMessage("Registration successful!");
    return SUCCESS;
  }

  @Action(value = "checkEmail")
  public String checkEmail() {
    inputStream = new StringBufferInputStream((userService.isEmailAvailable(registeredEmail) ? "true" : "false"));
    return "stream";
  }

  @Action(value = "checkUsername")
  public String checkUsername() {
    inputStream = new StringBufferInputStream((userService.isUsernameAvailable(registeredUserName) ? "true" : "false"));
    return "stream";
  }

  @Action(value = "checkUserData")
  public String checkUserData() {
    inputStream = new StringBufferInputStream((userService.isUserDataCorrect(username, password) ? "true" : "false"));
    return "stream";
  }

  @Action(value = "login")
  public String login() {

    return "home";
  }

}
